const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const regexpConstant = require('./regexp-constant');

function checkPath(rule, fileDirPath) {
    const regexpObj = rule.regexp;
    const filebasename = path.parse(fileDirPath).name;

    const whitelistRegexArray = rule.whitelist || [];
    const isWhiteMatch = whitelistRegexArray.some((regex) => regex.test(filebasename));
    if (isWhiteMatch) return {isMatch: true};

    const fileStat = fs.statSync(fileDirPath);

    let matchExt = '*';
    if (fileStat.isFile()) {
        matchExt = path.extname(fileDirPath);
    }
    let regexp = regexpObj;
    // 正则表达式名称，如果没有映射匹配，则是custom
    let name = 'custom';
    if (_.isPlainObject(regexpObj)) {
        regexp = regexpObj[matchExt] || regexpObj['*'];
    }
    // 使用映射的正则表达式
    if (_.isString(regexp)) {
        name = regexp;
        regexp = regexpConstant[regexp];
    }
    const isMatch = regexp.test(filebasename);
    return {isMatch, regexp, name};
}

module.exports = checkPath;
